﻿Imports System.ComponentModel
Imports System.Data.SqlClient

Public Class ExpenseTypes

    Public WithEvents expenseTypeList As ExpenseTypeList = expenseTypeList.GetList()
    Private WithEvents expenseTypeClass As ExpenseTypeClass
    Public WithEvents oWindowList As OpenedWindowList = OpenedWindowList.GetList()
    Private WithEvents oWindow As OpenedWindowClass

    Dim expensesTypeDB As New IETrackerDataClassesDataContext
    Dim frmIsDirty As Boolean = False
    Private _pageIsValid As Boolean = True
    Dim editFlag As Integer
    Dim al As New ArrayList

#Region "Window Events"

    Private Sub ExpenseTypes_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Dim ied As IEnumerable(Of OpenedWindowClass) = From d In oWindowList Where d.WindowID = Me.Name
        oWindowList.Remove(ied.First)

        If Application.Current.Windows.Count = 1 Then
            Application.Current.Windows(0).Activate()
        End If
    End Sub

    Private Sub ExpenseTypes_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        If frmIsDirty Then
            If MessageBox.Show("There are unsaved entries. Do you really want to exit?", "Exit", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.No Then
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub ExpenseTypes_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        noSelectedData()
        HookupChangeEventHandlers()
        LoadSubHeader()
    End Sub
#End Region

#Region "Support Procedures"
    Sub sortData()
        Dim iexpense As IEnumerable(Of ExpenseTypeClass) = From d In expenseTypeList Order By d.ExpenseName
        For Each i In iexpense
            expenseTypeList.Remove(i)
            expenseTypeList.Add(i)
        Next
    End Sub

    Public Function FilterCompletedTasks(ByVal t As Object) As Boolean
        Dim _tasks As New ExpenseTypeClass
        _tasks = t
        Return _tasks.ExpenseName.ToUpper.Contains(searchBox.Text.ToUpper)
    End Function

    Private Sub HookupChangeEventHandlers()
        For Each expenseTypeClass As ExpenseTypeClass In expenseTypeList
            HookupChangeEventHandler(expenseTypeClass)
        Next
    End Sub
    Private Sub HookupChangeEventHandler(ByVal expenseTrans As ExpenseTypeClass)
        AddHandler expenseTrans.PropertyChanged, _
          AddressOf HandlePropertyChanged
    End Sub

    Private Sub HandlePropertyChanged( _
    ByVal sender As Object, _
    ByVal e As PropertyChangedEventArgs)

        Dim propName As String = e.PropertyName
        Dim myexpense As ExpenseTypeClass = CType(sender, ExpenseTypeClass)

        Dim propInfo As System.Reflection.PropertyInfo = _
          GetType(ExpenseTypeClass).GetProperty(propName)
        Dim value As Object = _
          propInfo.GetValue(myexpense, Nothing)
    End Sub

#End Region

#Region "Set Defaults"
    Sub LoadSubHeader()
        If expenseTypeList.Count > 1 Then
            ExpanderText.Text = expenseTypeList.Count & " records found"
        Else
            ExpanderText.Text = expenseTypeList.Count & " record found"
        End If

    End Sub

    Sub noSelectedData()
        listBoxExpense.SelectedIndex = -1
        frmIsDirty = False
        setButtonProperties()
        mainOverlay.Visibility = Visibility.Visible
    End Sub


    Sub setButtonProperties()
        If frmIsDirty Then
            RibbonButtonSave.IsEnabled = True
            RibbonButtonCancel.IsEnabled = True
            RibbonButtonDelete.IsEnabled = True
            'RibbonButtonNew.IsEnabled = False
        Else
            RibbonButtonSave.IsEnabled = False
            RibbonButtonCancel.IsEnabled = False
            RibbonButtonDelete.IsEnabled = False
            'RibbonButtonNew.IsEnabled = True
        End If
    End Sub

    Sub pageIsValid(ByVal sender As String, ByVal isValid As Boolean)
        Dim inArray As Boolean = False
        For i = 0 To al.Count - 1
            If al.Item(i) = sender Then
                If isValid Then
                    al.Remove(Trim(sender))
                End If
                inArray = True
                Exit For
            End If
        Next
        If Not inArray Then
            If Not isValid Then
                al.Add(Trim(sender))
            End If
        End If
        If al.Count > 0 Then
            _pageIsValid = False
        Else
            _pageIsValid = True
        End If
    End Sub
#End Region

#Region "Control Events"
    Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles searchBox.TextChanged
        If Not listBoxExpense Is Nothing Then
            Dim icview As ICollectionView = CollectionViewSource.GetDefaultView(expenseTypeList)
            'If icview.Filter Is Nothing Then
            icview.Filter = New Predicate(Of Object)(AddressOf FilterCompletedTasks)
            'Else
            'icview.Filter = Nothing
            'End If
        End If
    End Sub

    Private Sub searchBox_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles searchBox.GotFocus
        If searchBox.Text = "Search" Then
            searchBox.Text = Nothing
        End If
    End Sub

    Private Sub listBoxExpense_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxExpense.SelectionChanged
        If listBoxExpense.SelectedIndex >= 0 Then
            With listBoxExpense.SelectedValue
                TextBoxExpenseName.Text = .expensename
                CheckBoxIsAutodeduct.IsChecked = .expenseoneoff
                TextBoxComment.Text = .expenseComment
            End With

            mainOverlay.Visibility = Visibility.Collapsed
            editFlag = HelperClass.EditMode.Edit
            frmIsDirty = True
            setButtonProperties()
        Else
            HelperClass.ClearTextBox(GridExpense)
            HelperClass.ClearComboBox(GridExpense)
        End If

    End Sub


    Private Sub CheckBoxOneOff_Unchecked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles CheckBoxIsAutodeduct.Unchecked, CheckBoxIsAutodeduct.Checked
        frmIsDirty = True
        setButtonProperties()
    End Sub


    Private Sub TextBoxComment_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxComment.TextChanged
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub TextBoxExpenseName_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxExpenseName.TextChanged
        frmIsDirty = True
        setButtonProperties()
    End Sub
#End Region

#Region "RibbonButton Click events"

    Private Sub RibbonButtonCancel_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonCancel.Click
        If editFlag = HelperClass.EditMode.Add Then
            HelperClass.ClearTextBox(GridExpense)
            HelperClass.ClearComboBox(GridExpense)
            noSelectedData()
        ElseIf editFlag = HelperClass.EditMode.Edit Then

            If listBoxExpense.SelectedIndex >= 0 Then
                With listBoxExpense.SelectedItem
                    TextBoxExpenseName.Text = .expensename
                    CheckBoxIsAutodeduct.IsChecked = .expenseoneoff
                    TextBoxComment.Text = .expensecomment
                End With

            End If
            frmIsDirty = True
            setButtonProperties()
        End If
    End Sub


    Private Sub RibbonButtonDelete_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonDelete.Click
        Dim index As Integer = listBoxExpense.SelectedIndex
        If index >= 0 Then
            Try
                Dim warningString As String = "Do you really want to delete this transaction?" & ControlChars.Lf & ControlChars.Lf & listBoxExpense.SelectedItem.expenseName
                If System.Windows.MessageBox.Show(warningString, "Delete Transaction", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    Dim selectedExpenseTransactionID As Integer = listBoxExpense.SelectedValue.ExpenseTypeId

                    Dim deleteFromTransaction = From trans In expensesTypeDB.TransactionDescriptions _
                                                Where trans.TransactionDescriptionID = selectedExpenseTransactionID
                    expensesTypeDB.TransactionDescriptions.DeleteOnSubmit(deleteFromTransaction.First)
                    expensesTypeDB.SubmitChanges()

                    Dim iExpensesClass As IEnumerable(Of ExpenseTypeClass) = From d In expenseTypeList Where d.ExpenseTypeId = selectedExpenseTransactionID
                    expenseTypeList.Remove(iExpensesClass.First)

                    HelperClass.ClearTextBox(GridExpense)
                    HelperClass.ClearComboBox(GridExpense)
                    noSelectedData()
                End If

            
            Catch ex As Exception
                expensesTypeDB = New IETrackerDataClassesDataContext
                MessageBox.Show("Error encountered while deleting the record." & ControlChars.Lf & ControlChars.Lf & ex.message.tostring, "Delete Error", MessageBoxButton.OK, MessageBoxImage.Error)

            End Try
        End If
    End Sub

    Private Sub RibbonButtonNew_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonNew.Click
        mainOverlay.Visibility = Visibility.Collapsed
        editFlag = HelperClass.EditMode.Add

        listBoxExpense.SelectedIndex = -1
        HelperClass.ClearTextBox(GridExpense)
        HelperClass.ClearComboBox(GridExpense)
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub RibbonButtonSave_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonSave.Click
        pageIsValid(TextBoxExpenseName.Name, EntryValidation.ValidateText(TextBoxExpenseName))

        If _pageIsValid Then
            Try
                If editFlag = HelperClass.EditMode.Add Then

                    Dim saveNewTransactionDescription As New TransactionDescription
                    With saveNewTransactionDescription
                        .TransactionDescription = TextBoxExpenseName.Text
                        .IsAutoDeduct = CheckBoxIsAutodeduct.IsChecked

                    End With
                    expensesTypeDB.TransactionDescriptions.InsertOnSubmit(saveNewTransactionDescription)
                    expensesTypeDB.SubmitChanges()

                    Dim saveNewTransactionType As New TransactionType
                    With saveNewTransactionType
                        .TransactionTypeDescID = 2
                        .TransactionDescID = saveNewTransactionDescription.TransactionDescriptionID
                        .OneOff = CheckBoxIsOneOff.IsChecked
                    End With
                    expensesTypeDB.TransactionTypes.InsertOnSubmit(saveNewTransactionType)
                    expensesTypeDB.SubmitChanges()

                    expenseTypeClass = New ExpenseTypeClass(saveNewTransactionDescription.TransactionDescriptionID, TextBoxExpenseName.Text, CheckBoxIsAutodeduct.IsChecked)
                    expenseTypeList.Add(expenseTypeClass)
                    sortData()
                    editFlag = HelperClass.EditMode.Edit


                    Dim ctr As Integer = 0
                    For Each item In expenseTypeList
                        If item.ExpenseName = TextBoxExpenseName.Text Then
                            Exit For
                        End If
                        ctr += 1
                    Next
                    
                    listBoxExpense.SelectedIndex = ctr

                ElseIf editFlag = HelperClass.EditMode.Edit Then
                    Dim selectedExpenseItem As Integer = listBoxExpense.SelectedValue.ExpenseTypeId

                    Dim expenses = From trans In expensesTypeDB.TransactionDescriptions _
                          Where trans.TransactionDescriptionID = selectedExpenseItem

                    With expenses.First
                        .TransactionDescription = TextBoxExpenseName.Text
                        '.Comment = TextBoxComment.Text
                        .IsAutoDeduct = CheckBoxIsAutodeduct.IsChecked
                    End With
                    expensesTypeDB.SubmitChanges()

                    'reflect changes in list
                    With expenseTypeList.Where(Function(x) x.ExpenseTypeId = selectedExpenseItem).First
                        .ExpenseName = TextBoxExpenseName.Text
                        .ExpenseOneOff = CheckBoxIsAutodeduct.IsChecked
                        .ExpenseComment = TextBoxComment.Text
                    End With
                End If
                frmIsDirty = False
                setButtonProperties()
                LoadSubHeader()
            Catch ex As Exception
                MessageBox.Show("Error encountered while saving the record." & ControlChars.Lf & ControlChars.Lf & ex.message.tostring, "Save Error", MessageBoxButton.OK, MessageBoxImage.Error)

            End Try

        End If
    End Sub
#End Region

End Class
